package net.flintx.array;

/**
 * Created by flintx on 2018/1/13.
 */
public class CanPlaceFlowers {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        if (flowerbed.length == 1) {
            return flowerbed[0] == 0? n <= 1 : n == 0;
        }
        int sum = 0, ans = 0;
        for (int i = 0; i < flowerbed.length; i++) {
            sum += flowerbed[i];
            if (flowerbed[i] == 1 && i + 1 > sum) {
                int zeroCount = i + 1 - sum;
                ans += sum == 1? zeroCount >> 1 : (zeroCount - 1) >> 1;
                sum = i + 1;
            }
        }
        if (sum == 0) {
            ans = (flowerbed.length + 1) >> 1;
        } else if (flowerbed[flowerbed.length - 1] == 0) {
            ans += (flowerbed.length - sum) >> 1;
        }
        return ans >= n;
    }
}
